import { getGrayAuth, getBasicEditionAuth } from '@src/api/SettingApi';
import { getAsyncSystemFrameInitData } from '@src/api/InitDataApi';

async function getInitData() {
  let initData = {};
  try {
    const result = await getAsyncSystemFrameInitData({});

    initData = result?.data?.initJson || {};
    const isSuccess = result.succ;

    if (!isSuccess) {
      return null;
    }
  } catch (error) {
    console.error('getInitData 失败', error);
    return null;
  }

  try {
    window._init = JSON.stringify(initData);
  } catch (error) {
    console.error('initData 赋值失败');
  }
  return initData;
}

async function fetchGrayAuth() {
  let grayAuth = {};

  try {
    const { result } = await getGrayAuth();
    if (result) {
      grayAuth = result;
    }
  } catch (error) {
    console.error('Caused: getBasicEditionAuth -> error', error);
  }

  window.grayAuth = grayAuth;
}

// 获取售后宝基础版权限
async function fetchBasicEditionAuth() {
  let basicEditionAuth = {};

  try {
    const { data } = await getBasicEditionAuth();
    if (data) basicEditionAuth = data;
  } catch (error) {
    console.error('Caused: getBasicEditionAuth -> error', error);
  }

  window.basicEditionAuth = basicEditionAuth;
}

export async function getInitAuth() {
  return Promise.all([fetchGrayAuth(), fetchBasicEditionAuth(), getInitData()]);
}
